{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-05-22T03:53:05.058038Z",
     "start_time": "2025-05-22T03:53:00.069108Z"
    }
   },
   "source": [
    "import torch\n",
    "\n",
    "# 检查 CUDA 是否可用\n",
    "print(torch.cuda.is_available())\n",
    "\n",
    "if torch.cuda.is_available():\n",
    "    # 获取可用的 CUDA 设备数量\n",
    "    print(\"可用的 CUDA 设备数量:\", torch.cuda.device_count())\n",
    "    # 获取当前使用的 CUDA 设备索引\n",
    "    print(\"当前 CUDA 设备索引:\", torch.cuda.current_device())\n",
    "    # 获取指定索引 CUDA 设备的名称\n",
    "    print(\"当前 CUDA 设备名称:\", torch.cuda.get_device_name(0))\n",
    "\n",
    "    # 创建一个张量并将其移动到 CUDA 设备上\n",
    "    x = torch.tensor([1.0, 2.0]).cuda()\n",
    "    y = torch.tensor([3.0, 4.0]).cuda()\n",
    "    z = x + y\n",
    "    print(\"在 CUDA 上计算的结果:\", z)\n",
    "else:\n",
    "    print(\"CUDA 不可用\")"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "可用的 CUDA 设备数量: 1\n",
      "当前 CUDA 设备索引: 0\n",
      "当前 CUDA 设备名称: NVIDIA GeForce RTX 3060\n",
      "在 CUDA 上计算的结果: tensor([4., 6.], device='cuda:0')\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T04:04:32.511936Z",
     "start_time": "2025-05-22T04:04:30.835567Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import visdom\n",
    "import numpy as np\n",
    "\n",
    "# 创建 Visdom 连接\n",
    "viz = visdom.Visdom()\n",
    "\n",
    "# 生成一些数据点\n",
    "x = np.arange(1, 101)  # x轴从1到100\n",
    "y = x * 2 + np.random.randn(100) * 10  # y = 2x + 噪声\n",
    "\n",
    "# 绘制直线图\n",
    "viz.line(\n",
    "    Y=y,  # y轴数据\n",
    "    X=x,  # x轴数据\n",
    "    opts=dict(\n",
    "        title='简单直线图示例',\n",
    "        xlabel='X轴',\n",
    "        ylabel='Y轴',\n",
    "        showlegend=True\n",
    "    )\n",
    ")"
   ],
   "id": "f5f52cce7f337d0a",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting up a new session...\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'window_3e18efca1b72ee'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T06:15:32.644510Z",
     "start_time": "2025-05-22T06:15:32.298845Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import visdom\n",
    "import numpy as np\n",
    "\n",
    "vis = visdom.Visdom()\n",
    "\n",
    "# 线图示例\n",
    "vis.line(\n",
    "    X=np.arange(10),\n",
    "    Y=np.random.rand(10),\n",
    "    opts=dict(title='Random Line', showlegend=True)\n",
    ")\n",
    "\n",
    "# 散点图示例\n",
    "vis.scatter(\n",
    "    X=np.random.rand(100, 2),\n",
    "    Y=(np.random.rand(100) > 0.5).astype(int)+1,\n",
    "    opts=dict(title='2D Scatter', markersize=10)\n",
    ")"
   ],
   "id": "d7e332a06ad69e08",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting up a new session...\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'window_3e19021739b10c'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T06:18:27.719183Z",
     "start_time": "2025-05-22T06:18:27.445474Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import visdom\n",
    "import numpy as np\n",
    "\n",
    "vis = visdom.Visdom()\n",
    "\n",
    "# 初始化线图\n",
    "vis.line(\n",
    "    X=[0],\n",
    "    Y=[0.5],\n",
    "    win='loss',\n",
    "    opts=dict(title='Training Loss')\n",
    ")\n",
    "\n",
    "# 模拟训练过程\n",
    "for epoch in range(1, 10):\n",
    "    loss = np.random.rand() * 0.1 + 1.0/(epoch+1)\n",
    "    vis.line(\n",
    "        X=[epoch],\n",
    "        Y=[loss],\n",
    "        win='loss',\n",
    "        update='append'  # 关键参数，避免覆盖\n",
    "    )"
   ],
   "id": "71e0e7f1bed0a664",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting up a new session...\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T13:06:57.644930Z",
     "start_time": "2025-05-22T13:06:51.486704Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import visdom\n",
    "import numpy as np\n",
    "import time\n",
    "\n",
    "vis = visdom.Visdom(env='training_monitor')\n",
    "\n",
    "# 初始化所有窗口\n",
    "vis.line(X=[0], Y=[0], win='loss', opts=dict(title='Loss', legend=['Train', 'Val']))\n",
    "vis.line(X=[0], Y=[0], win='acc', opts=dict(title='Accuracy', legend=['Train', 'Val']))\n",
    "\n",
    "for epoch in range(1, 11):\n",
    "    # 模拟训练数据\n",
    "    train_loss = np.random.rand()*0.1 + 1.0/epoch\n",
    "    val_loss = np.random.rand()*0.1 + 1.2/epoch\n",
    "    train_acc = 1 - train_loss + np.random.rand()*0.1\n",
    "    val_acc = 1 - val_loss + np.random.rand()*0.1\n",
    "\n",
    "    # 更新损失曲线（两种方式等价）\n",
    "    vis.line(\n",
    "        X=[epoch], Y=[train_loss],\n",
    "        win='loss', name='Train',\n",
    "        update='append'\n",
    "    )\n",
    "    vis.line(\n",
    "        X=[epoch], Y=[val_loss],\n",
    "        win='loss', name='Val',\n",
    "        update='append'\n",
    "    )\n",
    "\n",
    "    # 更新准确率曲线\n",
    "    vis.line(\n",
    "        X=[epoch], Y=[train_acc],\n",
    "        win='acc', name='Train',\n",
    "        update='append'\n",
    "    )\n",
    "    vis.line(\n",
    "        X=[epoch], Y=[val_acc],\n",
    "        win='acc', name='Val',\n",
    "        update='append'\n",
    "    )\n",
    "\n",
    "    # 每5个epoch可视化一批样本\n",
    "    if epoch % 5 == 0:\n",
    "        samples = np.random.rand(16, 3, 64, 64)  # 模拟图像数据\n",
    "        vis.images(\n",
    "            samples,\n",
    "            win='samples',\n",
    "            opts=dict(title=f'Epoch {epoch} Samples')\n",
    "        )\n",
    "\n",
    "    time.sleep(0.5)  # 模拟训练时间"
   ],
   "id": "be24f90eab824f6d",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting up a new session...\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T13:20:05.553564Z",
     "start_time": "2025-05-22T13:20:05.309396Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import visdom\n",
    "import numpy as np\n",
    "\n",
    "vis=visdom.Visdom(env='training_monitor')\n",
    "\n",
    "Y=np.random.rand(100)\n",
    "\n",
    "old_scatter=vis.scatter(\n",
    "    X=np.random.rand(100,2),\n",
    "    Y=(Y[Y>0]+1.5).astype(int),\n",
    "    opts=dict(\n",
    "        legend=['Didnt', 'Update'], # 图例标签\n",
    "        xtickmin=-50, # x轴刻度最小值\n",
    "        xtickmax=50, # x轴刻度最大值\n",
    "        xtickstep=0.5, # x轴刻度间隔\n",
    "        ytickmin=-50, # y轴刻度最小值\n",
    "        ytickmax=50, # y轴刻度最大值\n",
    "        ytickstep=0.5, # y轴刻度间隔\n",
    "        markersymbol='cross-thin-open', # 标记符号\n",
    "    )\n",
    ")\n",
    "# 使用update_window_opts函数更新之前绘制的散点图的配置选项\n",
    "vis.update_window_opts(\n",
    "    win=old_scatter,\n",
    "    opts=dict(\n",
    "        legend=['2019年', '2020年'],\n",
    "        xtickmin=0,\n",
    "        xtickmax=1,\n",
    "        xtickstep=0.5,\n",
    "        ytickmin=0,\n",
    "        ytickmax=1,\n",
    "        ytickstep=0.5,\n",
    "        markersymbol='cross-thin-open',\n",
    "    ),\n",
    ")"
   ],
   "id": "8121cc8c272d4f6c",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting up a new session...\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'window_3e193d66425bc8'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T13:23:32.440039Z",
     "start_time": "2025-05-22T13:23:32.316443Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#带文本标签的散点图\n",
    "import visdom\n",
    "import numpy as np\n",
    "\n",
    "vis.scatter(\n",
    "    X=np.random.rand(6, 2),\n",
    "    opts=dict(\n",
    "        textlabels=['Label %d' % (i + 1) for i in range(6)]\n",
    "    )\n",
    ")"
   ],
   "id": "955ea1fd981c9d30",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'window_3e193de182e54c'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T13:29:57.131227Z",
     "start_time": "2025-05-22T13:29:56.991068Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#三维散点图\n",
    "import visdom\n",
    "import numpy as np\n",
    "# 设置环境\n",
    "vis=visdom.Visdom(env='training_monitor')\n",
    "# 绘制3D散点图\n",
    "vis.scatter(\n",
    "    # X轴数据 随机生成100行3列数据\n",
    "    X=np.random.rand(100, 3),\n",
    "    # Y轴数据 随机生成100行1列数据\n",
    "    Y=(Y + 1.5).astype(int),\n",
    "    opts=dict(\n",
    "        legend=['男性', '女性'], # 图例标签\n",
    "        markersize=5, # 标记大小\n",
    "        xtickmin=0, # x轴刻度最小值\n",
    "        xtickmax=2, # x轴刻度最大值\n",
    "        xlabel='数量', # x轴标签\n",
    "        xtickvals=[0, 0.75, 1.6, 2], # x轴刻度值\n",
    "        ytickmin=0, # y轴刻度最小值\n",
    "        ytickmax=2, # y轴刻度最大值\n",
    "        ytickstep=0.5, # y轴刻度间隔\n",
    "        ztickmin=0, # z轴刻度最小值\n",
    "        ztickmax=1, # z轴刻度最大值\n",
    "        ztickstep=0.5, # z轴刻度间隔\n",
    "    )\n",
    ")"
   ],
   "id": "f88bb5f2a14b83d7",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting up a new session...\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'window_3e193ec6ddf61c'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T13:41:03.048513Z",
     "start_time": "2025-05-22T13:41:02.715968Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "import visdom\n",
    "\n",
    "vis=visdom.Visdom(env='training_monitor')\n",
    "\n",
    "# 基本线图\n",
    "vis.line(\n",
    "    Y=np.random.rand(10),\n",
    "    opts=dict(title='Basic Line', markers=True)\n",
    ")\n",
    "\n",
    "# 多线带图例\n",
    "vis.line(\n",
    "    X=np.arange(20),\n",
    "    Y=np.column_stack([np.sin(np.arange(20)), np.cos(np.arange(20))]),\n",
    "    opts=dict(\n",
    "        title='Trig Functions',\n",
    "        legend=['Sin', 'Cos'],\n",
    "        linecolor=np.array([[255,0,0], [0,0,255]]),  # 红蓝双线\n",
    "        dash=np.array(['solid', 'dash'])\n",
    "    )\n",
    ")"
   ],
   "id": "e09b2edb939790fa",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting up a new session...\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'window_3e194053c99b0c'"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T13:44:31.077141Z",
     "start_time": "2025-05-22T13:44:30.694801Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#实线、虚线等不同线\n",
    "import visdom\n",
    "import numpy as np\n",
    "\n",
    "vis=visdom.Visdom(env='training_monitor')\n",
    "# 绘制三种线\n",
    "win = vis.line(\n",
    "    #  X轴数据 将三个在0和1之间的等差数列组成一个3列的矩阵\n",
    "    X=np.column_stack((\n",
    "        np.arange(0, 10),\n",
    "        np.arange(0, 10),\n",
    "        np.arange(0, 10),\n",
    "    )),\n",
    "    # Y轴数据 将三个在5和10之间的线性插值分别加上5、10后组成一个3列的矩阵\n",
    "    Y=np.column_stack((\n",
    "        np.linspace(5, 10, 10),\n",
    "        np.linspace(5, 10, 10) + 5,\n",
    "        np.linspace(5, 10, 10) + 10,\n",
    "    )),\n",
    "    opts={\n",
    "        'dash': np.array(['solid', 'dash', 'dashdot']),\n",
    "        'linecolor': np.array([\n",
    "            [0, 191, 255],\n",
    "            [0, 191, 255],\n",
    "            [255, 0, 0],\n",
    "        ]),\n",
    "        'title': '不同类型的线'\n",
    "    }\n",
    ")\n",
    "# 在之前创建的窗口win上继续绘制线条\n",
    "vis.line(\n",
    "    X=np.arange(0, 10), # X轴数据\n",
    "    Y=np.linspace(5, 10, 10) + 15, # Y轴数据\n",
    "    win=win, # 使用之前创建的窗口\n",
    "    name='4', # 线条名称\n",
    "    update='insert', # 更新方式为插入\n",
    "    opts={ # 绘制选项\n",
    "        'linecolor': np.array([ # 线条颜色\n",
    "            [255, 0, 0], # 红色\n",
    "        ]),\n",
    "        'dash': np.array(['dot']), # 线条样式 只包含点\n",
    "    }\n",
    ")"
   ],
   "id": "3557b60bd8854baa",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting up a new session...\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'window_3e1940cfc51f5a'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T13:54:39.154534Z",
     "start_time": "2025-05-22T13:54:39.025094Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#堆叠区域\n",
    "import visdom\n",
    "import numpy as np\n",
    "\n",
    "vis=visdom.Visdom(env='training_monitor')\n",
    "\n",
    "Y = np.linspace(0, 4, 200)\n",
    "win = vis.line(\n",
    "    Y=np.column_stack((np.sqrt(Y), np.sqrt(Y) + 2)),\n",
    "    X=np.column_stack((Y, Y)),\n",
    "    opts=dict(\n",
    "        fillarea=True, # 填充区域\n",
    "        showlegend=False, # 不显示图例\n",
    "        width=380, # 宽度\n",
    "        height=330, # 高度\n",
    "        ytype='log', # y轴类型\n",
    "        title='堆积面积图', # 标题\n",
    "        marginleft=30, # 左边距\n",
    "        marginright=30, # 右边距\n",
    "        marginbottom=80, # 底边距\n",
    "        margintop=30, # 上边距\n",
    "    ),\n",
    ")"
   ],
   "id": "a26ef49029b80d1d",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting up a new session...\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T14:10:08.664126Z",
     "start_time": "2025-05-22T14:10:08.533436Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#茎叶图\n",
    "import math\n",
    "import visdom\n",
    "import numpy as np\n",
    "vis=visdom.Visdom(env='training_monitor')\n",
    "\n",
    "Y = np.linspace(0, 2 * math.pi, 70)\n",
    "X = np.column_stack((np.sin(Y), np.cos(Y)))\n",
    "vis.stem(\n",
    "    X=X,\n",
    "    Y=Y,\n",
    "    opts=dict(legend=['正弦函数', '余弦函数'])\n",
    ")"
   ],
   "id": "63e7a1a49296e5af",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting up a new session...\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'window_3e19446440ebd4'"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T14:13:30.121304Z",
     "start_time": "2025-05-22T14:13:29.982589Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import math\n",
    "import numpy as np\n",
    "import visdom\n",
    "\n",
    "vis = visdom.Visdom(env='training_monitor')\n",
    "\n",
    "# 生成X轴数据（自变量：角度）\n",
    "angles = np.linspace(0, 2 * math.pi, 70)  # 0到2π的70个点\n",
    "\n",
    "# 生成Y轴数据（因变量：函数值）\n",
    "function_values = np.column_stack((np.sin(angles), np.cos(angles)))  # 两列：sin和cos\n",
    "\n",
    "vis.stem(\n",
    "    X=function_values,  # 茎顶的位置（Y轴值）\n",
    "    Y=angles,           # 茎的位置（X轴值）\n",
    "    opts=dict(\n",
    "        legend=['sin(θ)', 'cos(θ)'],\n",
    "        title='茎叶图：sin和cos函数对比',\n",
    "        xtickvals=np.arange(0, 7, 1).tolist(),      # 使用 .tolist() 转换为 Python 列表\n",
    "        xticklabels=['0', '1', '2', '3', '4', '5', '6'],\n",
    "        ytickvals=np.arange(-1, 1.5, 0.5).tolist()   # 同样使用 .tolist()\n",
    "    )\n",
    ")\n"
   ],
   "id": "18e05302923689f1",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting up a new session...\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'window_3e1944dc54d64c'"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 29
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-22T14:34:00.175234Z",
     "start_time": "2025-05-22T14:18:03.969577Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "from torchvision import datasets, transforms\n",
    "from torch.utils.data import DataLoader\n",
    "import visdom\n",
    "\n",
    "# 初始化Visdom\n",
    "vis = visdom.Visdom(env='MNIST_Experiment')\n",
    "\n",
    "# 定义简单CNN模型\n",
    "class SimpleCNN(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(SimpleCNN, self).__init__()\n",
    "        self.conv1 = nn.Conv2d(1, 10, kernel_size=5)\n",
    "        self.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n",
    "        self.fc1 = nn.Linear(320, 50)\n",
    "        self.fc2 = nn.Linear(50, 10)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = torch.relu(torch.max_pool2d(self.conv1(x), 2))\n",
    "        x = torch.relu(torch.max_pool2d(self.conv2(x), 2))\n",
    "        x = x.view(-1, 320)\n",
    "        x = torch.relu(self.fc1(x))\n",
    "        x = self.fc2(x)\n",
    "        return torch.log_softmax(x, dim=1)\n",
    "\n",
    "# 准备数据\n",
    "transform = transforms.Compose([transforms.ToTensor()])\n",
    "train_dataset = datasets.MNIST('./data', train=True, download=True, transform=transform)\n",
    "test_dataset = datasets.MNIST('./data', train=False, transform=transform)\n",
    "\n",
    "train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\n",
    "test_loader = DataLoader(test_dataset, batch_size=1000, shuffle=False)\n",
    "\n",
    "# 初始化模型和优化器\n",
    "model = SimpleCNN()\n",
    "optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)\n",
    "criterion = nn.NLLLoss()\n",
    "\n",
    "# 训练函数\n",
    "def train(epoch):\n",
    "    model.train()\n",
    "    for batch_idx, (data, target) in enumerate(train_loader):\n",
    "        optimizer.zero_grad()\n",
    "        output = model(data)\n",
    "        loss = criterion(output, target)\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "\n",
    "        if batch_idx % 100 == 0:\n",
    "            vis.line(\n",
    "                X=[epoch * len(train_loader) + batch_idx],\n",
    "                Y=[loss.item()],\n",
    "                win='training_loss',\n",
    "                update='append' if epoch + batch_idx > 0 else None,\n",
    "                opts=dict(title='Training Loss', xlabel='Iterations', ylabel='Loss')\n",
    "            )\n",
    "\n",
    "# 测试函数\n",
    "def test(epoch):\n",
    "    model.eval()\n",
    "    test_loss = 0\n",
    "    correct = 0\n",
    "    with torch.no_grad():\n",
    "        for data, target in test_loader:\n",
    "            output = model(data)\n",
    "            test_loss += criterion(output, target).item()\n",
    "            pred = output.argmax(dim=1, keepdim=True)\n",
    "            correct += pred.eq(target.view_as(pred)).sum().item()\n",
    "\n",
    "    test_loss /= len(test_loader.dataset)\n",
    "    accuracy = 100. * correct / len(test_loader.dataset)\n",
    "\n",
    "    vis.line(\n",
    "        X=[epoch],\n",
    "        Y=[test_loss],\n",
    "        win='test_loss',\n",
    "        update='append' if epoch > 0 else None,\n",
    "        opts=dict(title='Test Loss', xlabel='Epoch', ylabel='Loss')\n",
    "    )\n",
    "\n",
    "    vis.line(\n",
    "        X=[epoch],\n",
    "        Y=[accuracy],\n",
    "        win='test_accuracy',\n",
    "        update='append' if epoch > 0 else None,\n",
    "        opts=dict(title='Test Accuracy', xlabel='Epoch', ylabel='Accuracy (%)')\n",
    "    )\n",
    "\n",
    "    # 可视化一些测试样本和预测结果\n",
    "    if epoch % 5 == 0:\n",
    "        sample_data = next(iter(test_loader))[0][:10]\n",
    "        outputs = model(sample_data)\n",
    "        preds = outputs.argmax(dim=1)\n",
    "\n",
    "        vis.images(\n",
    "            sample_data,\n",
    "            opts=dict(title=f'Predictions at Epoch {epoch}', caption=' '.join(str(p.item()) for p in preds))\n",
    "        )\n",
    "\n",
    "# 运行训练和测试\n",
    "for epoch in range(1, 11):\n",
    "    train(epoch)\n",
    "    test(epoch)"
   ],
   "id": "d1e41f37ea89ca04",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting up a new session...\n",
      "100.0%\n",
      "100.0%\n",
      "100.0%\n",
      "100.0%\n"
     ]
    }
   ],
   "execution_count": 30
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T03:30:40.449397Z",
     "start_time": "2025-05-23T03:30:40.143532Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from torch.utils.tensorboard import SummaryWriter\n",
    "writer = SummaryWriter(log_dir = './runs/test')\n",
    "writer.log_dir\n",
    "for i in range(10):\n",
    "    writer.add_scalar('mul', i*i, i)"
   ],
   "id": "54001af3c201e56c",
   "outputs": [],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T03:40:17.028491Z",
     "start_time": "2025-05-23T03:40:12.804092Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from tensorboardX import SummaryWriter\n",
    "writer = SummaryWriter(log_dir = './runs/test')\n",
    "for i in range(10):\n",
    "    writer.add_scalar('mul', i*i, i)\n",
    "writer.close()  # 确保关闭 writer"
   ],
   "id": "262e255f66b4456d",
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T07:36:29.177537Z",
     "start_time": "2025-05-23T07:36:28.850218Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from torch.utils.tensorboard import SummaryWriter\n",
    "\n",
    "writer = SummaryWriter(log_dir = './runs/test')\n",
    "for i in range(10):\n",
    "    writer.add_scalar('指数', 3**i, global_step=i)"
   ],
   "id": "72b9f2b1de6ee3c7",
   "outputs": [],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T07:44:23.207289Z",
     "start_time": "2025-05-23T07:44:23.192815Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from torch.utils.tensorboard import SummaryWriter\n",
    "\n",
    "writer = SummaryWriter(log_dir = './runs/test')\n",
    "for i in range(10):\n",
    "    writer.add_scalars('多变量输入', {'0.9的指数': 0.9**i, '2的指数': 2**i}, i)\n",
    "writer.close()"
   ],
   "id": "10d7df2fb23fee1c",
   "outputs": [],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T07:49:16.537966Z",
     "start_time": "2025-05-23T07:49:16.466495Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import torch\n",
    "from torch.utils.tensorboard import SummaryWriter\n",
    "\n",
    "# 初始化\n",
    "writer = SummaryWriter('./runs/demo_histogram')\n",
    "model = torch.nn.Linear(10, 2)  # 简单线性层\n",
    "\n",
    "for step in range(100):\n",
    "    # 模拟训练过程\n",
    "    model.weight.data += 0.01 * torch.randn_like(model.weight)\n",
    "\n",
    "    # 每10步记录一次权重分布\n",
    "    if step % 10 == 0:\n",
    "        writer.add_histogram('linear/weight', model.weight, step)\n",
    "        writer.add_histogram('linear/bias', model.bias, step)"
   ],
   "id": "cd6f1f36a5bb4b1c",
   "outputs": [],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T08:01:29.272636Z",
     "start_time": "2025-05-23T08:01:27.282834Z"
    }
   },
   "cell_type": "code",
   "source": "pip list",
   "id": "40bdfd46ca89b522",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Package                   VersionNote: you may need to restart the kernel to use updated packages.\n",
      "\n",
      "------------------------- --------------\n",
      "absl-py                   2.2.2\n",
      "anyio                     4.9.0\n",
      "argon2-cffi               23.1.0\n",
      "argon2-cffi-bindings      21.2.0\n",
      "arrow                     1.3.0\n",
      "asttokens                 3.0.0\n",
      "async-lru                 2.0.5\n",
      "attrs                     25.3.0\n",
      "babel                     2.17.0\n",
      "backcall                  0.2.0\n",
      "beautifulsoup4            4.13.4\n",
      "bleach                    6.2.0\n",
      "certifi                   2025.4.26\n",
      "cffi                      1.17.1\n",
      "charset-normalizer        3.4.2\n",
      "colorama                  0.4.6\n",
      "comm                      0.2.1\n",
      "debugpy                   1.8.11\n",
      "decorator                 5.1.1\n",
      "defusedxml                0.7.1\n",
      "exceptiongroup            1.2.0\n",
      "executing                 0.8.3\n",
      "fastjsonschema            2.21.1\n",
      "filelock                  3.18.0\n",
      "fqdn                      1.5.1\n",
      "fsspec                    2025.5.0\n",
      "grpcio                    1.71.0\n",
      "h11                       0.16.0\n",
      "httpcore                  1.0.9\n",
      "httpx                     0.28.1\n",
      "idna                      3.10\n",
      "importlib_metadata        8.5.0\n",
      "ipykernel                 6.29.5\n",
      "ipython                   8.15.0\n",
      "isoduration               20.11.0\n",
      "jedi                      0.19.2\n",
      "Jinja2                    3.1.6\n",
      "json5                     0.12.0\n",
      "jsonpatch                 1.33\n",
      "jsonpointer               3.0.0\n",
      "jsonschema                4.23.0\n",
      "jsonschema-specifications 2025.4.1\n",
      "jupyter_client            8.6.3\n",
      "jupyter_core              5.7.2\n",
      "jupyter-events            0.12.0\n",
      "jupyter-lsp               2.2.5\n",
      "jupyter_server            2.16.0\n",
      "jupyter_server_terminals  0.5.3\n",
      "jupyterlab                4.4.2\n",
      "jupyterlab_pygments       0.3.0\n",
      "jupyterlab_server         2.27.3\n",
      "Markdown                  3.8\n",
      "MarkupSafe                3.0.2\n",
      "matplotlib-inline         0.1.6\n",
      "mistune                   3.1.3\n",
      "mpmath                    1.3.0\n",
      "nbclient                  0.10.2\n",
      "nbconvert                 7.16.6\n",
      "nbformat                  5.10.4\n",
      "nest-asyncio              1.6.0\n",
      "networkx                  3.2.1\n",
      "notebook                  7.4.2\n",
      "notebook_shim             0.2.4\n",
      "numpy                     2.0.2\n",
      "overrides                 7.7.0\n",
      "packaging                 24.2\n",
      "pandocfilters             1.5.1\n",
      "parso                     0.8.4\n",
      "pickleshare               0.7.5\n",
      "pillow                    11.2.1\n",
      "pip                       25.1\n",
      "platformdirs              4.3.7\n",
      "prometheus_client         0.22.0\n",
      "prompt-toolkit            3.0.43\n",
      "protobuf                  6.31.0\n",
      "psutil                    5.9.0\n",
      "pure-eval                 0.2.2\n",
      "pycparser                 2.22\n",
      "Pygments                  2.19.1\n",
      "python-dateutil           2.9.0.post0\n",
      "python-json-logger        3.3.0\n",
      "pywin32                   308\n",
      "pywinpty                  2.0.15\n",
      "PyYAML                    6.0.2\n",
      "pyzmq                     26.2.0\n",
      "referencing               0.36.2\n",
      "requests                  2.32.3\n",
      "rfc3339-validator         0.1.4\n",
      "rfc3986-validator         0.1.1\n",
      "rpds-py                   0.25.1\n",
      "scipy                     1.13.1\n",
      "Send2Trash                1.8.3\n",
      "setuptools                78.1.1\n",
      "six                       1.17.0\n",
      "sniffio                   1.3.1\n",
      "soupsieve                 2.7\n",
      "stack-data                0.2.0\n",
      "sympy                     1.13.1\n",
      "tensorboard               2.19.0\n",
      "tensorboard-data-server   0.7.2\n",
      "tensorboardX              2.6.2.2\n",
      "terminado                 0.18.1\n",
      "tinycss2                  1.4.0\n",
      "tomli                     2.2.1\n",
      "torch                     2.6.0+cu124\n",
      "torchaudio                2.6.0+cu124\n",
      "torchvision               0.21.0+cu124\n",
      "tornado                   6.4.2\n",
      "traitlets                 5.14.3\n",
      "types-python-dateutil     2.9.0.20250516\n",
      "typing_extensions         4.12.2\n",
      "uri-template              1.3.0\n",
      "urllib3                   2.4.0\n",
      "visdom                    0.2.4\n",
      "wcwidth                   0.2.5\n",
      "webcolors                 24.11.1\n",
      "webencodings              0.5.1\n",
      "websocket-client          1.8.0\n",
      "Werkzeug                  3.1.3\n",
      "wheel                     0.45.1\n",
      "zipp                      3.21.0\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T08:02:29.382839Z",
     "start_time": "2025-05-23T08:02:24.070351Z"
    }
   },
   "cell_type": "code",
   "source": "pip install opencv-python",
   "id": "1cdf4c02df9d24c6",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple\n",
      "Collecting opencv-python\n",
      "  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/a4/7d/f1c30a92854540bf789e9cd5dde7ef49bbe63f855b85a2e6b3db8135c591/opencv_python-4.11.0.86-cp37-abi3-win_amd64.whl (39.5 MB)\n",
      "     ---------------------------------------- 0.0/39.5 MB ? eta -:--:--\n",
      "     ------- -------------------------------- 7.3/39.5 MB 41.2 MB/s eta 0:00:01\n",
      "     ---------------------- ---------------- 23.1/39.5 MB 60.8 MB/s eta 0:00:01\n",
      "     --------------------------------------  39.3/39.5 MB 65.8 MB/s eta 0:00:01\n",
      "     --------------------------------------- 39.5/39.5 MB 58.4 MB/s eta 0:00:00\n",
      "Requirement already satisfied: numpy>=1.17.0 in c:\\users\\kongyue\\.conda\\envs\\pytorch_stu\\lib\\site-packages (from opencv-python) (2.0.2)\n",
      "Installing collected packages: opencv-python\n",
      "Successfully installed opencv-python-4.11.0.86\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T08:03:17.843588Z",
     "start_time": "2025-05-23T08:03:17.718149Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import cv2 as cv\n",
    "print(cv.__version__)"
   ],
   "id": "2aacb22de4c3ab5e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4.11.0\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T08:09:37.533775Z",
     "start_time": "2025-05-23T08:09:36.843173Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from torch.utils.tensorboard import SummaryWriter\n",
    "import cv2 as cv\n",
    "\n",
    "# 初始化\n",
    "writer = SummaryWriter('./runs/demo_images')\n",
    "\n",
    "for i in range(1,4):\n",
    "    # 确保图像维度正确并使用正确的 dataformats 参数\n",
    "    writer.add_image('countdown', cv.cvtColor(cv.imread('./image/{}.jpg'.format(i)), cv.COLOR_BGR2RGB),global_step=i,  dataformats='HWC')\n",
    "writer.close()"
   ],
   "id": "1e250094734a33e0",
   "outputs": [],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T11:10:37.706254Z",
     "start_time": "2025-05-23T11:10:34.168128Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import torch\n",
    "import numpy as np\n",
    "from torchvision import models,transforms\n",
    "from PIL import Image\n",
    "from torch.utils.tensorboard import SummaryWriter\n",
    "\n",
    "vgg16 = models.vgg16() # 这里下载预训练好的模型\n",
    "\n",
    "transform_2 = transforms.Compose([\n",
    "    transforms.Resize(224),\n",
    "    transforms.CenterCrop(224),\n",
    "    transforms.ToTensor(),\n",
    "\n",
    "    transforms.Lambda(lambda x: torch.index_select(x, 0, torch.LongTensor([2, 1, 0]))),\n",
    "    transforms.Lambda(lambda x: x*255),\n",
    "    transforms.Normalize(mean = [103.939, 116.779, 123.68],\n",
    "                          std = [ 1, 1, 1 ]),\n",
    "])\n",
    "\n",
    "cat_img = Image.open('./image/1.jpg')\n",
    "vgg16_input=transform_2(cat_img)[np.newaxis]# 因为pytorch的是分批次进行的，所以我们这里建立一个批次为1的数据集\n",
    "print(vgg16_input.shape)\n",
    "\n",
    "#开始前向传播，打印输出值\n",
    "raw_score = vgg16(vgg16_input)\n",
    "raw_score_numpy = raw_score.data.numpy()\n",
    "print(raw_score_numpy.shape, np.argmax(raw_score_numpy.ravel()))\n",
    "\n",
    "#将结构图在tensorboard进行展示\n",
    "with SummaryWriter(log_dir='./runs/demo_graph', comment='vgg16') as writer:\n",
    "    writer.add_graph(vgg16, (vgg16_input,))"
   ],
   "id": "73ee689129c49325",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([1, 3, 224, 224])\n",
      "(1, 1000) 89\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T11:11:57.614620Z",
     "start_time": "2025-05-23T11:11:57.458695Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import torchvision\n",
    "from torch.utils.tensorboard import SummaryWriter\n",
    "\n",
    "writer = SummaryWriter('runs/vector')\n",
    "mnist = torchvision.datasets.MNIST('./data', download=False)\n",
    "writer.add_embedding(\n",
    "    mnist.data.reshape((-1, 28 * 28))[:30,:],\n",
    "    metadata=mnist.targets[:30],\n",
    "    label_img = mnist.data[:30,:,:].reshape((-1, 1, 28, 28)).float() / 255,\n",
    "    global_step=0\n",
    ")\n",
    "writer.close()"
   ],
   "id": "5222070d2145f91e",
   "outputs": [],
   "execution_count": 21
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T11:19:05.155616Z",
     "start_time": "2025-05-23T11:19:05.121777Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from torch.utils.tensorboard import SummaryWriter\n",
    "import random\n",
    "\n",
    "writer = SummaryWriter('runs/hparams_simulation')\n",
    "\n",
    "# 模拟3组不同超参数的训练结果\n",
    "for i in range(3):\n",
    "    lr = 0.01 * (i+1)  # 学习率递增\n",
    "    batch_size = 32 * (i+1)  # 批量大小递增\n",
    "\n",
    "    # 模拟指标（随机值演示）\n",
    "    accuracy = 0.8 + random.uniform(-0.1, 0.1)\n",
    "    loss = 0.2 + random.uniform(-0.05, 0.05)\n",
    "\n",
    "    # 记录当前超参数组合和指标\n",
    "    writer.add_hparams(\n",
    "        {'lr': lr, 'batch_size': batch_size, 'exp_id': i},\n",
    "        {'hparam/accuracy': accuracy, 'hparam/loss': loss}\n",
    "    )\n",
    "\n",
    "writer.close()"
   ],
   "id": "502b75f68325871b",
   "outputs": [],
   "execution_count": 23
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T11:43:12.214241Z",
     "start_time": "2025-05-23T11:43:12.186854Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "from torch.utils.tensorboard import SummaryWriter\n",
    "np.random.seed(20250523)\n",
    "# 生成100个随机整数 范围为2到上限，并将其存储再labels变量中\n",
    "labels=np.random.randint(2, size=100)\n",
    "# 生成100个随机浮点数 范围为[0,1] ，并将其存储再predictions变量中\n",
    "predictions=np.random.randn(100)\n",
    "writer = SummaryWriter('runs/demo_pr')\n",
    "# 添加PR曲线 用于评估二分类问题的性能\n",
    "writer.add_pr_curve('pr_curve', labels, predictions, global_step=0)\n",
    "writer.close()"
   ],
   "id": "18bbda68d840bf52",
   "outputs": [],
   "execution_count": 27
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-23T11:45:08.328845Z",
     "start_time": "2025-05-23T11:45:07.492868Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "from torch.utils.tensorboard import SummaryWriter\n",
    "\n",
    "# 定义简单模型\n",
    "class SimpleModel(nn.Module):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        self.fc = nn.Linear(10, 1)\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.fc(x)\n",
    "\n",
    "# 初始化\n",
    "model = SimpleModel()\n",
    "criterion = nn.MSELoss()\n",
    "optimizer = optim.SGD(model.parameters(), lr=0.01)\n",
    "writer = SummaryWriter('runs/simple_model_experiment')\n",
    "\n",
    "# 模拟数据\n",
    "inputs = torch.randn(100, 10)\n",
    "targets = torch.randn(100, 1)\n",
    "\n",
    "# 训练循环\n",
    "for epoch in range(100):\n",
    "    optimizer.zero_grad()\n",
    "    outputs = model(inputs)\n",
    "    loss = criterion(outputs, targets)\n",
    "    loss.backward()\n",
    "    optimizer.step()\n",
    "\n",
    "    # 记录标量\n",
    "    writer.add_scalar('Loss/train', loss.item(), epoch)\n",
    "\n",
    "    # 记录直方图\n",
    "    writer.add_histogram('fc/weight', model.fc.weight, epoch)\n",
    "    writer.add_histogram('fc/bias', model.fc.bias, epoch)\n",
    "\n",
    "    # 每10个epoch记录一次梯度\n",
    "    if epoch % 10 == 0:\n",
    "        for name, param in model.named_parameters():\n",
    "            writer.add_histogram(f'gradients/{name}', param.grad, epoch)\n",
    "\n",
    "# 记录模型图\n",
    "dummy_input = torch.randn(1, 10)\n",
    "writer.add_graph(model, dummy_input)\n",
    "\n",
    "# 记录超参数和最终指标\n",
    "writer.add_hparams(\n",
    "    {'lr': 0.01, 'batch_size': 100},\n",
    "    {'hparam/loss': loss.item()}\n",
    ")\n",
    "\n",
    "writer.close()"
   ],
   "id": "1119b60a8e26934a",
   "outputs": [],
   "execution_count": 28
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch_stu",
   "language": "python",
   "name": "pytorch_stu"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
